package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public void saveFloverAndDish(DishDto dishDto) {
         /*
        1.拿到整个数据
        2.分析得，这数据分别保存在2张表中，所以说要分别保存
        3.把菜品信息保存在菜品表中
        4.把口味情况，保存在口味表中
         */
        //保存菜品
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();//取出口味
        Long id = dishDto.getId();//获取菜品id
        List<DishFlavor> collect = flavors.stream().map((item) -> {//item为每一个口味对象,因为传递过来的口味对象没有和菜品表id绑定
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());//此时口味表中就有相应数据
        dishFlavorService.saveBatch(collect);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);//根据id获取当前dish对象
        DishDto dishDto = new DishDto();//把数据封装到DishDto里面
        BeanUtils.copyProperties(dish, dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<DishFlavor>();//一个菜品对应多种口味
        lqw.eq(DishFlavor::getDishId, dish.getId());//设置查询字段
        List<DishFlavor> dishFlavor = dishFlavorService.list(lqw);//获取口味
        dishDto.setFlavors(dishFlavor);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        /*
            1.对dish表中基本数据进行更新
            2.对dishFlavor表中原来数据进行删除
            3.对新口味添加到dishFlavor中
         */
        this.updateById(dishDto);//1

        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lqw);

        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> collect = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(collect);
    }

    @Override
    public List<DishDto> dishList(Dish dish) {
         /*
        根据菜品id显示关联的菜品
               进一步修改，之前是查询了菜品信息，没有查询口味情况
               然后用户界面需要传递一个包含口味的json，来用于展示口味信息。于是就行修改。
         */
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        if (dish.getCategoryId() != null) {
            lqw.eq(Dish::getCategoryId, dish.getCategoryId());
        }
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = this.list(lqw);

        /*
        修改,根据菜品id查询口味。并封装
         */
        List<DishDto> dishDtos = list.stream().map((item) -> {//此时的item为每一个dish对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            /*
            封装菜品名字
             */
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            if (categoryName != null) {
                dishDto.setCategoryName(categoryName);
            }
            /*
            查询每个菜品id,根据id查询每个菜品口味
             */
            Long itemId = item.getId();//dishId
            LambdaQueryWrapper<DishFlavor> dflqw = new LambdaQueryWrapper<>();
            dflqw.eq(DishFlavor::getDishId, itemId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dflqw);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return dishDtos;
    }

    @Override
    public void updateDish(Long id, List<Long> ids) {
        if (id == 1 && ids.size() > 1) {//表示批量起售
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.in(Dish::getId, ids);//select * from dish where dishid in(1,2)
            List<Dish> dishList = this.list(lqw);

            List<Dish> collect = dishList.stream().map((item) -> {//item为dish对象
                item.setStatus(1);
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(collect);
        } else if (id == 0 && ids.size() > 1) {//批量停售
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.in(Dish::getId, ids);//select * from dish where dishid in(1,2)
            List<Dish> dishList = this.list(lqw);

            List<Dish> collect = dishList.stream().map((item) -> {//item为dish对象
                item.setStatus(0);
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(collect);
        } else {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.in(Dish::getId, ids);//select * from dish where dishid in(1,2)
            List<Dish> dishList = this.list(lqw);

            List<Dish> collect = dishList.stream().map((item) -> {//item为dish对象
                if (item.getStatus() == 0) {
                    item.setStatus(1);
                } else {
                    item.setStatus(0);
                }
                return item;
            }).collect(Collectors.toList());
            this.updateBatchById(collect);
        }
    }


    @Override
    public void delete(List<Long> ids) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId, ids);
        List<Dish> dishList = this.list(lqw);

        List<Long> collect = dishList.stream().map((item) -> {
            log.info("此时删除里面的item对象为{}", item);
            if (item.getStatus() == 1) {//表示起售
                throw new CustomException("先将商品停售--然后在删除！");
            }
            Long itemId = item.getId();
            return itemId;
        }).collect(Collectors.toList());
        this.removeByIds(collect);
    }

    @Override
    public Page<DishDto> pageDishManage(int page, int pageSize, String name) {
        Page<Dish> dishPageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        if (name != null) {
            dlqw.like(Dish::getName, name);
        }
        dlqw.orderByDesc(Dish::getSort);
        this.page(dishPageInfo, dlqw);

        Page<DishDto> dishDtoPageInfo = new Page<DishDto>(page, pageSize);//此时这dishDtoPage里面数据为空
        BeanUtils.copyProperties(dishPageInfo, dishDtoPageInfo, "records");//除了records里面的数据其他的都复制
        List<Dish> dishs = dishPageInfo.getRecords();//获取dish
        List<DishDto> dishDtos = dishs.stream().map((item) -> {//item为dish对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);//此时就只差categoryName
            Long categoryId = item.getCategoryId();//获取分类id
            Category category = categoryService.getById(categoryId);//根据菜品id获取菜品分类对象
            String categoryName = category.getName();//获取分类名称
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPageInfo.setRecords(dishDtos);
        return dishDtoPageInfo;
    }
}
